package com.cj.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cj.model.Bonus;
import com.cj.model.Department;
import com.cj.model.Employee;
import com.cj.model.Post;
import com.cj.model.SalaryRecord;
import com.cj.model.Timecard;
import com.cj.utils.StrUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;

public class EmployeeController extends Controller {
	
	public void login() {
		String username = getPara("username");
		String password = getPara("password");
		Employee employee = Employee.me.login(username, password);
		if(employee != null) {
			setSessionAttr("employee", employee);	
			renderJson("status", "success");
		} else {
			renderJson("status", "fail");
		}
	}
	
	public void logout() {
		getSession().removeAttribute("employee");
		render("login.jsp");
	}
	
	public void index() {
		List<Employee> employees = Employee.me.getAllEmployees();
		List<Department> departments = Department.me.getAllDepartments();
		List<Post>	posts = Post.me.getAllPosts();
		setAttr("departments", departments);
		setAttr("posts", posts);
		setAttr("employees", employees);
		render("userInfo.jsp");
	}
	
	public void profile() {
		render("profile.jsp");
	}
	
	public void editProfile() {
		editProilePre();
		render("editProfile.jsp");
	}
	
	private void editProilePre() {
		List<Department> departments = Department.me.getAllDepartments();
		setAttr("departments", departments);
		Employee employee = getSessionAttr("employee");
		String empPhoto = employee.getStr("empPhoto");
		if(StrUtil.isBlank(empPhoto)) {
			employee.set("empPhoto", "default.png");
		} else {
			empPhoto += "?" + new Date();
			employee.set("empPhoto", empPhoto);
		}
		Integer deptId = employee.getInt("deptId");
		List<Post> posts = Post.me.getPostsByDept(deptId);
		setAttr("posts", posts);
	}
	
	public void password() {
		render("updatePassword.jsp");
	}
	
	public void updatePassword() {
		Employee employee = getSessionAttr("employee");
		String password = getPara("password");
		employee.set("password", password);
		setSessionAttr("employee", employee);
		employee.update();
		renderJson("result", 1);
	}
	
	public void employeeInfo() {
		String empId = getPara("id");
		Map<String, Object> jsonResult = new HashMap<>();
		Employee employee = Employee.me.getEmployeeById(Integer.parseInt(empId));
		if(employee != null) {
			Post post = Post.me.findById(employee.get("postId"));
			List<Post> posts = Post.me.getPostsByDept((Integer)post.get("deptId")); 
			jsonResult.put("status", "success");
			jsonResult.put("employee", employee);
			jsonResult.put("posts", posts);
		} else {
			jsonResult.put("status", "fail");
		}
		renderJson("result", jsonResult);
	}
	
	public void edit() {
		if(!updateEmployee()) {
			renderError(404);
		};
		redirect("/employee");
	}
	
	public void delete() {
		Boolean result = true;
		Integer empId = getParaToInt("empId");
		List<SalaryRecord> salaryRecords = SalaryRecord.me.getSalaryRecordsByEmployee(empId);
		List<Bonus> bonuses = Bonus.me.getBonusByEmployee(empId);
		List<Timecard> timecards = Timecard.me.getTimecardsByEmployee(empId);
		if(salaryRecords != null && !salaryRecords.isEmpty()) {
			result = false;
		}
		if(result && bonuses != null && !bonuses.isEmpty()) {
			result = false;
		}
		if(result && timecards != null && !timecards.isEmpty()) {
			result = false;
		}
		if(result) {
			Employee.me.deleteById(empId);
		}
		renderJson("result", result);
	}
	
	public void saveProfile() {
		if(updateEmployee()) {
			setAttr("editStatus", "success");
		} else {
			setAttr("editStatus", "error");
		}
		Employee oldEmployee = getSessionAttr("employee");
		Integer empId = oldEmployee.getInt("empId");
		Employee newEmployee = Employee.me.getEmployeeById(empId);
		setSessionAttr("employee", newEmployee);
		editProilePre();
		render("editProfile.jsp");
	}
	
	private boolean updateEmployee() {
		Employee employee = new Employee();
		UploadFile uploadFile = getFile("empPic");
		employee = getModel(Employee.class);
		try {
			uploadImage(uploadFile, employee);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		employee.update();
		return true;
	}
	
	public void add() {
		Employee employee = new Employee();
		UploadFile uploadFile = getFile("empPic");
		employee = getModel(Employee.class);
		try {
			uploadImage(uploadFile, employee);
		} catch (IOException e) {
			e.printStackTrace();
			renderError(404);
		}
		Integer maxId = Employee.me.getMaxID();
		if(maxId == null) {
			maxId = -1;
		}
		String empNo = StrUtil.getNo("E", "0000", maxId + 1);
		employee.remove("empId");
		employee.set("password", "123456");
		employee.set("empNo", empNo).save();
		redirect("/employee");
	}
	
	private void uploadImage(UploadFile uploadFile, Employee employee) throws IOException {
		if(uploadFile != null) {
			String filePrefixName = getPara("employee.empNo");
			String uploadFileName = uploadFile.getFileName();
			String extension = uploadFileName.substring(uploadFileName.lastIndexOf("."));
			String targetFileName = filePrefixName + extension;
			System.out.println(targetFileName);
			saveFile(uploadFile, targetFileName);
			employee.set("empPhoto", targetFileName);
		}
	}
	
	private void saveFile(UploadFile uploadFile, String fileName) throws IOException {
		File sourceFile = uploadFile.getFile();
		FileInputStream fis = new FileInputStream(sourceFile);
		File targetDir = new File(PathKit.getWebRootPath() + "/resources/employeePic");
		if(!targetDir.exists()) {
			targetDir.mkdirs();
		}
		File targetFile = new File(targetDir, fileName);
		if(targetFile.exists()) {
			targetFile.delete();
		}
		targetFile.createNewFile();
		FileOutputStream fos = new FileOutputStream(targetFile);
        byte[] bts = new byte[300];
        while (fis.read(bts, 0, 300) != -1) {
        	fos.write(bts, 0, 300);
        }
        fos.close();
        fis.close();
        sourceFile.delete();
	}
	
	public void nameById() {
		Integer id = getParaToInt("id");
		Employee employee = Employee.me.findById(id);
		if(employee != null) {
			String name = employee.getStr("empName");
			renderJson("name", name);
		} else {
			renderJson("name", "");
		}
	}
	
}
